#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
民法典数据库定期维护任务
"""

from pymongo import MongoClient
from datetime import datetime, timedelta
import json

def maintenance_tasks():
    """执行定期维护任务"""
    print("=" * 60)
    print("🔧 民法典数据库定期维护")
    print("=" * 60)
    
    try:
        client = MongoClient("mongodb://localhost:27017/")
        db = client['civil_code_db']
        collection = db['civil_code_articles']
        
        maintenance_log = {
            "maintenance_time": datetime.now().isoformat(),
            "tasks": []
        }
        
        # 1. 索引维护
        print("🔍 索引维护:")
        try:
            # 重建索引统计信息
            collection.reindex()
            print("   ✅ 索引重建完成")
            maintenance_log["tasks"].append({
                "task": "index_rebuild",
                "status": "success",
                "message": "索引重建完成"
            })
        except Exception as e:
            print(f"   ❌ 索引重建失败: {str(e)}")
            maintenance_log["tasks"].append({
                "task": "index_rebuild", 
                "status": "failed",
                "error": str(e)
            })
        
        # 2. 数据完整性检查
        print("\n📊 数据完整性检查:")
        total_count = collection.count_documents({})
        if total_count == 1260:
            print("   ✅ 数据完整性正常")
            maintenance_log["tasks"].append({
                "task": "data_integrity_check",
                "status": "success", 
                "total_articles": total_count
            })
        else:
            print(f"   ⚠️ 数据不完整: {total_count}/1260")
            maintenance_log["tasks"].append({
                "task": "data_integrity_check",
                "status": "warning",
                "total_articles": total_count,
                "expected": 1260
            })
        
        # 3. 清理过期数据
        print("\n🗑️ 清理过期数据:")
        
        # 清理过期的搜索历史（30天前）
        thirty_days_ago = datetime.now() - timedelta(days=30)
        search_history = db['search_history']
        
        deleted_count = search_history.delete_many({
            "created_at": {"$lt": thirty_days_ago.isoformat()}
        }).deleted_count
        
        print(f"   清理过期搜索历史: {deleted_count}条")
        maintenance_log["tasks"].append({
            "task": "cleanup_search_history",
            "status": "success",
            "deleted_count": deleted_count
        })
        
        # 4. 数据库压缩
        print("\n💾 数据库压缩:")
        try:
            # MongoDB的压缩操作
            db.command("compact", "civil_code_articles")
            print("   ✅ 数据库压缩完成")
            maintenance_log["tasks"].append({
                "task": "database_compact",
                "status": "success"
            })
        except Exception as e:
            print(f"   ⚠️ 数据库压缩: {str(e)}")
            maintenance_log["tasks"].append({
                "task": "database_compact",
                "status": "warning",
                "message": str(e)
            })
        
        # 5. 生成维护报告
        print("\n📄 维护任务完成:")
        success_tasks = len([t for t in maintenance_log["tasks"] if t["status"] == "success"])
        total_tasks = len(maintenance_log["tasks"])
        
        print(f"   成功完成: {success_tasks}/{total_tasks} 项任务")
        
        # 保存维护日志
        log_file = f"maintenance_log_{datetime.now().strftime('%Y%m%d_%H%M%S')}.json"
        with open(log_file, 'w', encoding='utf-8') as f:
            json.dump(maintenance_log, f, ensure_ascii=False, indent=2, default=str)
        
        print(f"   📁 维护日志已保存: {log_file}")
        
        client.close()
        return True
        
    except Exception as e:
        print(f"❌ 维护任务失败: {str(e)}")
        return False

if __name__ == "__main__":
    maintenance_tasks()
